define(function (require, exports, module) {
    var angular = require('angular');
    require("pagination");
    require("angular-ui");
    require("/public/js/plugins/select2/select2");
    require('/public/js/myservice/contract/contract-common');
    var dialog = require("dialogplus");
    var myMath = require('/public/js/myservice/common/my-math');
    var util = require("util");
    var api_prefix = G_CONFIG["api_prefix"]; //api前缀

    angular.module('ContractPerformance', [])
        .filter('percent', function () {
            return function (num) {
                return num * 100;
            }
        })
        .filter('sumSignAmount', function () {
            return function (incomes) {
                var amount = 0;
                $.each(incomes, function (i, d) {
                    if (d['__type'] == 'delete') {
                        return;
                    }
                    amount = myMath.add(amount, parseFloat(d.achievement_amount));
                });
                return amount;
            }
        })
        .filter('remainSignAmount', function () {
            return function (incomes, contract) {
                var amount = 0;
                $.each(incomes, function (i, d) {
                    if (d['__type'] == 'delete') {
                        return;
                    }
                    amount = myMath.add(amount, parseFloat(d.achievement_amount));
                });
                if (contract) {
                    return myMath.sub(contract.income_amount, amount);
                    //if (contract.contract_property_id == '7f83719a-fce8-11e4-bed8-00155d02c832'
                    //    || contract.contract_property_id == '7f8422d0-fce8-11e4-bed8-00155d02c832') {
                    //    //云链签约-直属区域/云链签约-联营区域
                    //    //收入金额汇总 = 签约金额
                    //    return myMath.sub(contract.sign_amount, amount);
                    //} else {
                    //    //其他：收入金额汇总=结算金额
                    //    return myMath.sub(contract.balance_amount, amount);
                    //}
                }

                return 0;
            }
        })
        .filter('signOrBalanceAmount', function () {
            return function (contract) {
                if (contract) {
                    return contract.income_amount;
                    //if (contract.contract_property_id == '7f83719a-fce8-11e4-bed8-00155d02c832'
                    //    || contract.contract_property_id == '7f8422d0-fce8-11e4-bed8-00155d02c832') {
                    //    //云链签约-直属区域/云链签约-联营区域
                    //    //收入金额汇总 = 签约金额
                    //    return contract.sign_amount;
                    //} else {
                    //    //其他：收入金额汇总=结算金额
                    //    return contract.balance_amount;
                    //}
                }
                return 0;
            }
        })
        .filter('signOrBalanceLabel', function () {
            return function (contract) {
                //if (contract) {
                //    if (contract.contract_property_id == '7f83719a-fce8-11e4-bed8-00155d02c832'
                //        || contract.contract_property_id == '7f8422d0-fce8-11e4-bed8-00155d02c832') {
                //        //云链签约-直属区域/云链签约-联营区域
                //        //收入金额汇总 = 签约金额
                //        return '签约金额';
                //    } else {
                //        //其他：收入金额汇总=结算金额
                //        return '结算金额';
                //    }
                //}
                return '收入金额';
            }
        })
        .controller('contractPerformanceCtrl', ['$scope', '$routeParams', 'contractCommonService', function ($scope, $routeParams, contractCommonService) {
            //合同业绩信息
            $scope.contractBaseInfo = {customer_property: 0, contract_status: 0};
            $scope.contractPfmInfo = {
                signAchievements: [],
                paymentAchievement: []
            };

            //产品列表
            var contractId = $routeParams.id;
            if (contractId) {
                //编辑模式先设为只读（复核状态），避免复核的合同先显示编辑按钮再隐藏导致的刷新
                $scope.contractBaseInfo.contract_status = 1;
            }

            //获取合同信息
            $scope.loadContract = function (contractId) {
                if (contractId) {
                    //合同基本信息
                    contractCommonService.getContract(contractId, function (data) {
                        $scope.contractBaseInfo = data.contract;
                        $scope.$applyAsync();
                    });

                    //合同业绩信息
                    var url = api_prefix + 'contract/get-sign-achievement';
                    $.ajax({
                        url: url,
                        type: 'post',
                        dataType: 'json',
                        data: {contractId: contractId},
                        success: function (res) {
                            if (res.retCode === "0") {
                                var data = res.data;
                                data.created_on = $scope.contractBaseInfo.created_on;
                                $scope.contractPfmInfo = data;
                                if (!$scope.contractPfmInfo.signAchievements[0].manager_name) {
                                    $scope.contractPfmInfo.signAchievements[0].manager_name = '';
                                }
                                $scope.$applyAsync();
                            } else {
                                util.alert(res.errMsg);
                            }
                        },
                        error: function () {
                            util.alert('系统维护，请稍候重试！');
                        }
                    });
                }
            };

            //下拉框设置
            //业绩归属人
            $scope.ddlConfigBelongBy = {
                allowClear: false,
                ajax: {
                    url: api_prefix + "erp-interface/get-users",
                    dataType: 'json',
                    delay: 250,
                    data: function (term) {
                        return {
                            keyword: term,
                            limit: 10
                        };
                    },
                    results: function (json, page) {
                        var data = [];
                        if (json.retCode === "0") {
                            data = json.data;
                        }
                        return {results: data};
                    },
                    processResults: function (data, page) {
                        // parse the results into the format expected by Select2.
                        // since we are using custom formatting functions we do not need to
                        // alter the remote JSON data
                        return {
                            results: data.items
                        };
                    },
                    cache: true
                },
                escapeMarkup: function (markup) {
                    return markup;
                }, // let our custom formatter work
                minimumInputLength: 1,
                onchange2: function (newVal, scope) {
                    if (scope) {
                        scope.belong_name = newVal.text;
                        scope.area_by = newVal.BUGUID;
                        scope.abu_by = newVal.AubGUID;
                        scope.department_by = newVal.DepartmentId
                        scope.department_name = newVal.DepartmentName;
                        scope.area_name = newVal.BUName;
                    }
                },
                formatResult: formatProposer,
                formatSelection: formatProposerSelection // omitted for brevity, see the source of this page
            };

            //ERP业绩归属人
            $scope.ddlConfigErpBelongBy = {
                allowClear: true,
                ajax: {
                    url: api_prefix + "erp-interface/get-users",
                    dataType: 'json',
                    delay: 250,
                    data: function (term) {
                        return {
                            keyword: term,
                            limit: 10
                        };
                    },
                    results: function (json, page) {
                        var data = [];
                        if (json.retCode === "0") {
                            data = json.data;
                        }
                        return {results: data};
                    },
                    processResults: function (data, page) {
                        // parse the results into the format expected by Select2.
                        // since we are using custom formatting functions we do not need to
                        // alter the remote JSON data
                        return {
                            results: data.items
                        };
                    },
                    cache: true
                },
                escapeMarkup: function (markup) {
                    return markup;
                }, // let our custom formatter work
                minimumInputLength: 1,
                onchange2: function (newVal, scope) {
                    if (scope) {
                        newVal || (newVal = {});
                        scope.erp_achievement_belong_name = newVal.text || '';
                        scope.erp_achievement_belong_abu = newVal.AubGUID || '';
                        scope.erp_achievement_belong_abu_owner = newVal.AbuOwnerGUID || '';
                        scope.erp_achievement_belong_bu_manager = newVal.BuManagerGUID || '';

                        scope.erp_achievement_belong_abu_name = newVal.AubName || '';
                        scope.erp_achievement_belong_abu_owner_name = newVal.AbuOwnerName || '';
                        scope.erp_achievement_belong_bu_manager_name = newVal.BuManagerName || '';
                    }
                }
            };

            //EPR客户经理
            $scope.ddlConfigManagerBy = {
                allowClear: true,
                ajax: {
                    url: api_prefix + "erp-interface/get-users",
                    dataType: 'json',
                    delay: 250,
                    data: function (term) {
                        return {
                            keyword: term,
                            limit: 10
                        };
                    },
                    results: function (json, page) {
                        var data = [];
                        if (json.retCode === "0") {
                            data = json.data;
                        }
                        return {results: data};
                    },
                    processResults: function (data, page) {
                        // parse the results into the format expected by Select2.
                        // since we are using custom formatting functions we do not need to
                        // alter the remote JSON data
                        return {
                            results: data.items
                        };
                    },
                    cache: true
                },
                escapeMarkup: function (markup) {
                    return markup;
                }, // let our custom formatter work
                minimumInputLength: 1,
                onchange2: function (newVal, scope) {
                    if (scope) {
                        scope.manager_name = newVal ? newVal.text : '';
                        scope.erp_achievement_belong_bu = newVal ? newVal.DepartmentId : ''
                        scope.erp_achievement_belong_bu_name = newVal ? newVal.DepartmentName : '';
                    }
                },
                formatResult: formatProposer,
                formatSelection: formatProposerSelection // omitted for brevity, see the source of this page
            };
            function formatProposer(repo) {
                if (repo.loading) return repo.text;

                var markup = '<div class="clearfix" style="width: 300px;">' +
                    '<div class="clearfix">' +
                    '<div class="col-sm-6">' + repo.UserName + '</div>' +
                    '<div class="col-sm-18">' + repo.BUName + '</div>' +
                    '</div></div>';

                return markup;
            }

            function formatProposerSelection(repo) {
                return repo.text;
            }

            /**
             * 拆分业绩
             * @param items
             */
            $scope.addSignAchievement = function (items, record) {
                var item;
                if (items == $scope.contractPfmInfo.paymentAchievement) {
                    item = {
                        receivable_item_id: record.receivable_item_id,
                        receivable_item_name: record.receivable_item_name,
                        money_category_item_id: record.money_category_item_id,
                        money_category_item_name: record.money_category_item_name,
                        editMode: 1,
                        received_time: record.received_time,
                        achievement_belong_time: record.achievement_belong_time,
                        __type: 'add'
                    };
                } else {
                    item = {
                        editMode: 1,
                        achievement_belong_time: record.achievement_belong_time,
                        __type: 'add'
                    };
                }

                items.push(item);
            };

            /**
             * 修改业绩
             * @type {number}
             */
            $scope.editSignAchievement = function (item, idx, items) {
                //先保存原始数据
                item.orginalData = angular.copy(item);
                item.editMode = 2;

                //获取当前修改的人物下拉框
                var n = -2;
                var it;
                for (var i = idx; it = items[i]; i--) {
                    if (it.editMode == 1 || it.editMode == 2) {
                        //每点开一个，会生成2个相同class的元素
                        n += 2;
                    }
                }

                setTimeout(function () {
                    $(".idBelongBy1").eq(n).select2("data", {
                        id: item.achievement_id,
                        text: item.belong_name
                    });
                    $(".idManagerBy1").eq(n).select2("data", {
                        id: item.achievement_id,
                        text: item.manager_name
                    });
                    $(".idBelongBy2").eq(n).select2("data", {
                        id: item.achievement_id,
                        text: item.belong_name
                    });
                    $(".idManagerBy2").eq(n).select2("data", {
                        id: item.achievement_id,
                        text: item.manager_name
                    });
                    $(".idErpBelongBy").eq(n).select2("data", {
                        id: item.achievement_id,
                        text: item.erp_achievement_belong_name
                    });
                    $scope.$applyAsync();
                }, 0)

            };

            /**
             * 删除收入
             * @type {number}
             */
            $scope.delSignAchievement = function (item, idx, items) {
                var it;
                var sum = 0;
                for (var i = 0; it = items[i]; i++) {
                    if (!it.editMode || it.editMode == 0) {
                        sum++;
                    }
                }
                if (sum <= 1) {
                    util.alert('不可删除唯一确定的业绩！');
                    return
                }
                util.confirm('确定要删除此业绩吗？', {
                    ok: function () {
                        if (item.__type == 'add') {
                            items.splice(idx, 1);
                        } else {
                            angular.extend(item, {__type: 'delete', editMode: 3});
                        }
                        $scope.$applyAsync();
                    }
                });
            };

            /**
             * 保存收入信息
             * @type {number}
             */
            $scope.saveSignAchievement = function (item) {
                if (!item.achievement_amount) {
                    util.alert('业绩金额不能为空');
                    return;
                } else if (!(parseFloat(item.achievement_amount) > 0)) {
                    util.alert('业绩金额必须为数值且大于0');
                    return;
                } else {
                    var arr = item.achievement_amount.split(".");
                    if (arr.length > 2) {
                        util.alert('业绩金额只能输入1位小数点');
                        return
                    } else if (arr[1] && arr[1].length > 2) {
                        util.alert('业绩金额请保留2位小数');
                        return
                    }
                }

                if (!item.belong_by) {
                    util.alert('业绩归属人不能为空');
                    return;
                }

                // 当合同类型为非直属区域时：ERP相关业绩归属不是必填项
                // 云链签约-直属区域 : 7f83719a-fce8-11e4-bed8-00155d02c832
                // 明源签约-直属区域 : 54f8a2b7-fce7-11e4-bed8-00155d02c832
                //10月1日业绩规则变了，这个字段不用强控
                //if($scope.contractBaseInfo.contract_property_id === '7f83719a-fce8-11e4-bed8-00155d02c832' || $scope.contractBaseInfo.contract_property_id === '54f8a2b7-fce7-11e4-bed8-00155d02c832'){
                //    if (!item.manager_by) {
                //        util.alert('ERP客户经理不能为空');
                //        return;
                //    }
                //}

                item.editMode = 0;
                $scope.$applyAsync();
            };

            /**
             * 取消保存
             * @type {number}
             */
            $scope.cancelSignAchievement = function (item, idx, items) {
                if (item.editMode == 1) {
                    items.splice(idx, 1);
                } else {
                    angular.extend(item, item.orginalData);
                    item.editMode = 0;
                }

            };

            /**
             * 计算金额
             *
             */
            $scope.restSignAmount = 0;
            $scope.signOrBalanceAmount = '';
            $scope.calTotalSignAmount = function () {
                var sum = 0;

                var items = $scope.contractPfmInfo.signAchievements;
                if (items) {
                    for (var i = 0; i < items.length; i++) {
                        var item = items[i];
                        if (item['__type'] == 'delete') {
                            return
                        }
                        sum += parseFloat(item.achievement_amount || 0);
                    }
                }

                $scope.restSignAmount = $scope.contractBaseInfo.income_amount - sum;
                $scope.signOrBalanceAmount = '收入金额';
                //if($scope.contractPfmInfo.contract_property_name=='云链签约-直属区域'|| $scope.contractPfmInfo.contract_property_name=='云链签约-联营区域'){
                //    $scope.restSignAmount = $scope.contractBaseInfo.sign_amount - sum;
                //    $scope.signOrBalanceAmount = '签约金额';
                //}else{
                //    $scope.restSignAmount = $scope.contractBaseInfo.balance_amount - sum;
                //    $scope.signOrBalanceAmount = '结算金额';
                //}
            };

            //能否保存判断
            $scope.saveEnabled = function () {
                var sign = $scope.contractPfmInfo.signAchievements;
                var payment = $scope.contractPfmInfo.paymentAchievement;
                var n = 0;
                $.grep(sign, function (d, i) {
                    if (d.editMode == 1 || d.editMode == 2) {
                        n++;
                    }
                });
                $.grep(payment, function (d, i) {
                    if (d.editMode == 1 || d.editMode == 2) {
                        n++;
                    }
                });
                return n;
            };

            /**
             * 保存信息
             */
            $scope.save = function () {
                var url = api_prefix + 'contract/save-sign-achievement';
                if ($scope.contractBaseInfo.is_cancelled == 0) {
                    var data = {
                        contractId: contractId,
                        drawProjectNumeric: $scope.contractPfmInfo.draw_project_numeric,
                        projectNumeric: $scope.contractPfmInfo.project_numeric,
                        achievementRemark: $scope.contractBaseInfo.achievement_remark,
                        signAchievements: $scope.contractPfmInfo.signAchievements,
                        paymentAchievements: $scope.contractPfmInfo.paymentAchievement
                    };
                }
                $scope.calTotalSignAmount();
                if ($scope.restSignAmount >= 0) {
                    $.ajax({
                        url: url,
                        type: 'post',
                        dataType: 'json',
                        data: data,
                        success: function (res) {
                            if (res.retCode === "0") {
                                util.alert('保存成功');
                                $scope.loadContract(contractId);
                            } else {
                                util.alert(res.errMsg);
                            }
                        },
                        error: function () {
                            util.alert('系统维护，请稍候重试！');
                        }
                    });
                } else {
                    util.alert('签约业绩金额总和不能大于' + $scope.signOrBalanceAmount);
                }
            };

            //页面初始化
            $scope.init = function () {
                $scope.loadContract(contractId);
            };
            $scope.init();
        }]);
});
